package com.firesrc.mail.search;

import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import jodd.db.DbThreadSession;
import jodd.db.pool.CoreConnectionPool;

import com.firesrc.bean.Record;
import com.firesrc.db.DBManager;
import com.firesrc.util.IU;

public abstract class AbstractSearchMail implements SearchMailStrategy {

	public static Set getMailListFromText(String aa) {
		Set mailSet = new HashSet();
		Pattern pattern = Pattern.compile("[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+");
		Pattern pattern2 = Pattern
				.compile("[\\w\\-_]+(\\.[\\w\\-_]+)+([\\w\\-\\.,@?^=%&amp;:/~\\+#]*[\\w\\-\\@?^=%&amp;/~\\+#])?");
		Matcher matcher = pattern.matcher(aa);

		Matcher matcher2 = pattern2.matcher(aa);
		// Map<String, String> httpMap = new HashMap<String, String>();
		// while (matcher2.find()) {
		// System.err.println("JsoupUtil.pr()" + matcher2.group());
		// }
		while (matcher.find()) {
			mailSet.add(matcher.group());
		}

		filterDupMails(mailSet);

		return mailSet;
	}

	private static void filterDupMails(Set mailSet) {
		Set<String> filterSet = new HashSet<String>();
		filterSet.add("domainadm@hichina.com");
		filterSet.add("agent1347@agent.dns.com.cn");
		filterSet.add("domian@whoisprotectionservices.net");

		for (String string : filterSet) {
			if (mailSet.contains(string)) {
				mailSet.remove(string);
			}
		}
	}

	public AbstractSearchMail() {
		super();
	}

	@Override
	public Set<Record> getRecordFromUrl(String url, String keyword) {
		Set<String> mailSet = getMailListFromUrl(url);
		Record record = null;
		Set<Record> set = new HashSet<Record>();
		if (mailSet.size() == 0) {
			CoreConnectionPool cp = DBManager.getPublicConnectionPool();
			new DbThreadSession(cp);
			Record insertRecord = new Record();
			insertRecord.setId(IU.g());
			insertRecord.setUrl(url);
			insertRecord.setKeyword(keyword);
			jodd.db.oom.sqlgen.DbEntitySql.insert(insertRecord).query().executeUpdateAndClose();
			return set;
		}
		for (String mail : mailSet) {
			record = new Record();
			record.setId(IU.g());
			record.setKeyword(keyword);
			record.setMail(mail);
			record.setUrl(url);
			set.add(record);
		}
		return set;

	}

	@Override
	public abstract Set getMailListFromUrl(String string);

}